package com.webull.information.center.carwler.job.branch;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.webull.information.center.carwler.common.model.BaseNewsRel;
import com.webull.information.center.carwler.common.model.CarwlerJobConfig;
import com.webull.information.center.carwler.common.util.BranchNewsUtil;
import com.webull.information.center.carwler.common.util.CarwlerJobStateUtil;
import com.webull.information.center.carwler.common.util.eljob.ElasticJobUtil;
import com.webull.information.center.carwler.dao.CarwlerJobConfigDao;
import com.webull.information.center.carwler.dao.CarwlerNewsDao;
import com.webull.information.client.service.InfoNewsService;

/**
 * 处理各分支同步过来的news数据
 */
@Component
public class Base_Process_BranchRel_Job implements SimpleJob {
    protected final Logger logger = LogManager.getLogger(getClass());
    private @Autowired
    CarwlerJobStateUtil carwlerJobStateUtil;
    private @Autowired
    CarwlerNewsDao carwlerNewsDao;
    private @Autowired
    CarwlerJobConfigDao carwlerJobConfigDao;
    private @Autowired
    InfoNewsService infoNewsService;
    private final String collectJob = "base_Process_BranchRel_Job";


	@Override
	public void execute(ShardingContext context) {
		int sharding = Optional.ofNullable(context).map(v -> v.getShardingItem()).orElse(-1);
		int totalCount = Optional.ofNullable(context).map(v -> v.getShardingTotalCount()).orElse(-1);

		carwlerJobStateUtil.assertCarwlerJobConfig(true);

		logger.info("Base_Process_Branch_Job start:" + ArrayUtils.toString(sharding) + ",totalCount:" + totalCount);

		List<CarwlerJobConfig> carwlerJobConfigs = Optional.ofNullable(carwlerJobConfigDao.searchBranchCarwler())
				.orElse(new ArrayList<>());
		List<CarwlerJobConfig> shardRegions = Optional
				.ofNullable(ElasticJobUtil.shardingItems(context, carwlerJobConfigs)).orElse(carwlerJobConfigs);
		for (CarwlerJobConfig tgs : shardRegions) {
			processBaseRel(tgs);
		}
	}


    private void processBaseRel(CarwlerJobConfig carwlerJobConfig) {
        logger.info("Base_Process_Branch_Job.processBaseRel div size{};carwlerJobConfig:{};", carwlerJobConfig);
        CarwlerJobConfig config = new CarwlerJobConfig();
        BeanUtils.copyProperties(carwlerJobConfig, config, "pastNewsId", "pastBaRelId");
        try {

            logger.info("Base_Process_Branch_Job.processBaseRel start collectJob{} div ,carwlerJobConfig:{} ",
                    collectJob, config);

            Integer lastId_ = Optional.ofNullable(carwlerJobConfigDao.getPastBaRelIdByCarwler(config.getCarwler())).orElse(0);
            do1:
            while (true) {
                List<BaseNewsRel> baseNewsRels = carwlerNewsDao.searchBaseRel0(config.getBaseRelTable(), lastId_);
                if (baseNewsRels == null || baseNewsRels.isEmpty()) break do1;

                baseNewsRels.forEach(v -> {
                    try {
                       if (v.getTargetType() != null) {
                            infoNewsService.addNewsInfoRel(v.getTargetId(), BranchNewsUtil.genNewsRelType(v.getTargetType()), v.getNewsId());
                        }
                    } catch (Exception e) {
                        logger.error("Base_Process_Branch_Job error", e);
                    }
                });

                lastId_ = baseNewsRels.get(baseNewsRels.size() - 1).getId();
                config.setPastBaRelId(lastId_);
                carwlerJobConfigDao.update(config);
                logger.info("Base_Process_Branch_Job.processBaseRel mid collectJob{} div ,carwlerJobConfig:{},lastId_{}",
                        collectJob, config.getCarwler(), lastId_);
            }
            logger.info("Base_Process_Branch_Job.processBaseRel end collectJob{} div ,carwlerJobConfig:{},lastId_{}",
                    collectJob, config.getCarwler(), lastId_);
        } catch (Exception e) {
            logger.error("Base_Process_Branch_Job.processBaseRel collectJob div error:" + config, e);
        }
    }


}
